import datetime
import pymysql
import sys
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S')


class insert_etl_db:

    def __init__(self, jine_sum, channel_id, client_id):

        self.host = "ip"
        self.port = 110
        self.user = "user"
        self.passwd = "pwd"
        self.db = "db"
        self.date = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime('%Y%m%d')
        self.sql = "insert into tb_channel_cost(date,channel_id,client_id,cost) VALUES (" + self.date + ",'" + channel_id + "','" + client_id + "'," + jine_sum + ")"

    def insert_mysql(self):

        db = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db,
                             write_timeout=30)
        # 通过cursor创建游标
        cursor = db.cursor()
        try:
            cursor.execute(self.sql)
            # 提交SQL
            db.commit()
            logging.info(self.sql + "---插入成功！")
        except Exception as e:
            print(datetime.datetime.now(), e)
            # 发生错误时回滚
            db.rollback()
            # 关闭数据库连接
        finally:
            db.close()


if __name__ == '__main__':
    jine_sum = sys.argv[1]
    channel_id = sys.argv[2]
    client_id = sys.argv[3]
    insert_etl_db(jine_sum, channel_id, client_id).insert_mysql()
